<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in carListIntro" :key="cartInfo.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="!!cartInfo.isChecked"
              @change="checkCartInfoState(cartInfo)">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeNum('sub', cartInfo)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1" class="itxt"
              @click="changeNum('change', cartInfo, $event)">
            <a href="javascript:void(0)" class="plus" @click="changeNum('add', cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a href="#none" class="sindelet" @click="showDelMode(cartInfo.skuId)">删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>


      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDelDataMode">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{ selectedCount }}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） :</em>
          <i class="summoney">{{ selectdPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
    <!-- 使用Dialog组件 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header>
        提示
      </template>
      <template>
        您真的要删除 {{ isDelOne ? '此条' : '所选中' }} 商品数据吗？
      </template>
      <template v-slot:footer>
        <div class="btn-footer">
          <button class="btn" @click="visible = false">取消</button>
          <button class="btn primary" @click="delShopCartIntro">确认</button>
        </div>

      </template>
    </Dialog>
  </div>

</template>

<script>
import { reqShopCartListData, reqChangeShopCartInfoState, reqUpdateAllSkuInfoState, reqDelOnShopCartInfo, reqDeleteSelectedCartInfo, reqAddOrUpdateData } from "@/api"
import { skuNumReg } from "@/utils/reg"
export default {
  name: 'ShopCart',

  data() {
    return {
      carListIntro: [],
      visible: false,
      skuId: 0,
      isDelOne: true, //是否删除一条数据
      skuList: [],//确定要删除的数据
      otherList: [],//剩下不删除的数据
      timeId: 0,
      num: 0
    }
  },
  computed: {
    // 1.全选与取消全选
    checkAll: {
      get() {
        return this.carListIntro.every(item => item.isChecked === 1);
      },
      async set(val) {
        // 当总按钮被选中的时候，则所有的小按钮也要被选中
        // console.log(val)
        // this.cartInfoList.forEach(item=>item.isChecked=val)
        let isChecked = val ? 1 : 0;
        // this.cartInfoList.forEach(item => {
        //   item.isChecked=isChecked
        //   // reqUpdateSkuInfoState(item.skuId, isCheck)
        //   this.checkCartInfoState({skuId:item.skuId,isChecked:1 - isChecked})
        // })

        // 批量更改商品选 中的状态
        const skuIdList = [];
        this.carListIntro.forEach(item => {
          item.isChecked = isChecked;
          skuIdList.push(item.skuId);
        });

        // 发送请求批量更新
        const res = await reqUpdateAllSkuInfoState(isChecked, skuIdList);
        if (res.code === 200) {
          alert('批量更新成功...');
        }
      }
    },
    // 2.计算所选商品件数
    selectedCount() {
      return this.carListIntro.reduce((prev, item) => prev + item.isChecked, 0)
    },
    // 3.计算所选商品总价
    selectdPrice() {
      return this.carListIntro.reduce((prev, item) => prev + item.skuPrice * item.skuNum * item.isChecked, 0)
    }
  },
  async mounted() {
    // 发送请求获取数据
    let { data, code } = await reqShopCartListData()
    // console.log(data)
    if (code === 200) {
      this.carListIntro = data[0] ? data[0].cartInfoList : []
    } else {
      console.log("失败了！")
    }

  },
  methods: {
    // 1. 选中与 取消选 中
    async checkCartInfoState(cartInfo) {
      // console.log('切换了...')
      let checked = 1 - cartInfo.isChecked;
      const res = await reqChangeShopCartInfoState(cartInfo.skuId, checked);
      // 可以少发一次请求 直接让页面按钮变成另一种状态
      cartInfo.isChecked = checked;
    },
    // 2.点击删除按钮显示对话框 
    showDelMode(skuId) {
      this.skuId = skuId
      this.visible = true
    },
    // 3.点击对话框确认按钮 删除数据
    async delShopCartIntro() {
      // 判断是否删除一条数据
      if (this.isDelOne) {
        let { code } = await reqDelOnShopCartInfo(this.skuId)
        if (code === 200) {
          this.carListIntro = this.carListIntro.filter(item => item.skuId != this.skuId)
          // 删除数据之后 隐藏对话框
          this.visible = false
        } else {
          console.log("失败了")
        }
        return
      }

      // 批量删除选中的数据 
      const { code } = await reqDeleteSelectedCartInfo(this.skuList)
      if (code === 200) {
        // 隐藏对话框
        this.visible = false
        // 将未被删除的otherList数组渲染页面
        this.carListIntro = this.otherList
      }
    },
    // 4.单击批量删除按钮时 显示对话框
    showDelDataMode() {
      // 其实每次批量删除数据弹出对话框的时候，都要清空原来的数组
      this.skuList = [],
        this.otherList = []
      // 显示对话框
      this.visible = true
      // 判断是删除一条数据还是多条数据
      this.isDelOne = false
      // 收集待删除的数据skuId
      this.carListIntro.forEach(item => {
        if (item.isChecked) {
          // 将待删除的数据存储到skuList中
          this.skuList.push(item.skuId)
        } else {
          // 5.5 将未删除的数据存到otherList数组当中 要将剩下的数据显示在页面上
          this.otherList.push(item)
        }
      })

    },
    // 5.购物车数量的变化
    changeNum(type, cartInfo, event) {
      // 判断是那种类型 switch case
      // 定义一变量num  赋值0
      // let num = 0
      // 购物车商品数量防抖
      switch (type) {
        case 'sub':
          this.num--
          cartInfo.skuNum--
          if (cartInfo.skuNum == 1) {
            cartInfo.skuNum = 1;
            this.num = 0
          }
          break;
        case 'add':
          this.num++
          cartInfo.skuNum++
          if (cartInfo.skuNum > 200) {
            cartInfo.skuNum = 200;
            this.num = 0
          }
          break;
        case 'change':
          // 直接更改数量
          let newValue = event.target.value;
          let oldValue = cartInfo.skuNum;
          if (skuNumReg.test(newValue)) {
            // 验证通过 说明是数字
            cartInfo.skuNum = event.target.value - 0;
            this.num = cartInfo.skuNum - oldValue;
            if (cartInfo.skuNum > 200) {
              cartInfo.skuNum = 200;
              this.num = 200 - oldValue;
            }
          } else {
            // 否则就是非数字或是非法值  让skuNum还等于原值
            // 赋原值是赋值不上的 赋值不成功
            // cartInfo.skuNum = oldValue

            // 只能通过此种方式来进行赋值
            event.target.value = oldValue;
            this.num = 0
          }
          break;

      }
      // 重新发送请求  差值
      // 如果有定时器先清空定时器
      if (this.timeId) clearTimeout(this.timeId)
      // 设置定时器 发送请求

      this.timeId = setTimeout(async () => {
        if (this.num == 0) return
        let res = await reqAddOrUpdateData(cartInfo.skuId, this.num)
        if (res.code === 200) {
          this.num = 0
          alert("数据更新成功")
        } else {
          alert("数据更新失败")
        }
      }, 500)


    }

  },
  watch: {
    visible: {
      immediate: true, // 一开始立即就监视
      handler() {
        if (this.visible) {
          document.documentElement.style.overflow = "hidden";
        } else {
          document.documentElement.style.overflow = "auto";
        }
      },
    },
  },
}

</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      &>div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        &>li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }


      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }


}

// 底部
.btn-footer {
  position: absolute;
  right: 40px;
  bottom: 20px;

  .btn {
    width: 62px;
    height: 32px;
    font-size: 14px;
    margin-left: 16px;
    border-width: 1px;
    border-radius: 10%;
    cursor: pointer;

    &.primary {
      background-color: rgb(102, 177, 255);
      color: #fff;
    }
  }
}
</style>